<template>
  <div class="home">
    <el-row class="row-container">
      <el-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4" class="left">
        <div class="filter-params">
          <el-form ref="form" label-width="auto" class="search-area">
            <el-form-item label="省">
              <el-select
                placeholder="请选择"
                @change="search($event, 'province')"
                v-model="selectProvice"
              >
                <el-option
                  v-for="item in province"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="市">
              <el-select placeholder="请选择" @change="search($event, 'city')" v-model="selectCity">
                <el-option
                  v-for="item in city"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="区">
              <el-select
                placeholder="请选择"
                v-model="selectDistrict"
                @change="search($event, 'district')"
              >
                <el-option
                  v-for="item in district"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="类型">
              <el-select placeholder="请选择" v-model="selectType">
                <el-option
                  v-for="item in types"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <div>
              <el-button type="primary" @click="saveData">保存</el-button>
                <el-alert
                  title="点击地图添加广告点位置, 点击标签显示全景图"
                  :closable="false"
                  type="warning">
                </el-alert>
            </div>
          </el-form>

          <gd-list :data="gdData" @remove="remove" @location="location" @set-label="setMarkerLabel"></gd-list>
        </div>
      </el-col>

      <el-col :xs="24" :sm="24" :md="12" :lg="18" :xl="20" class="right">
        <el-amap
          ref="map"
          vid="amapDemo"
          :center="center"
          :zoom="zoom"
          :events="events"
          :map-style="mapStyle"
          :amap-manager="amapManager"
        >
          <!-- <el-amap-marker v-for="(marker, index) in gdData" :key="index"  :position="marker.params[1].value.split(',')" :events="markerEvents" :draggable="true" :vid="index"></el-amap-marker> -->
        </el-amap>
      </el-col>
    </el-row>
<el-dialog title="查看广告牌" :visible.sync="showimg" fullscreen>
 <!-- <el-image :src="srcimg"></el-image> -->
 <iframe src="http://112.74.25.226:4098/index2.html" :style="{width: '100%', height: '100%'}" frameborder=”no” border=”0″ marginwidth=”0″ marginheight=”0″></iframe>
</el-dialog>
  </div>
</template>

<script>
import { lazyAMapApiLoaderInstance } from "vue-amap";
import GdList from "@/components/gd-list";

import { AMapManager } from "vue-amap";
let amapManager = new AMapManager();
import demoImage from '@/assets/gd.jpg';

export default {
  name: "Home",
  components: { GdList },
  data() {
    const vm = this
    return {
      zoom: 12,
      center: [114.305215, 30.592935],
      amapManager,
      markers: [],
      searchOption: {
        // city: '武汉',
        // citylimit: true
      },
      mapStyle: "amap://styles/92646ddbe2fb4fbaf38c3542fe3e9ea9",
      events: {
        init(o) {
          console.log(o.getCenter());
        },
        moveend() {},
        zoomchange() {},
        click() {
          console.log('map click......')
          vm.enableMouse()
        }
      },
      overlay: [],
      markerEvents: {
        click(e){
          console.log('marker click.....', e)

        },
        dragging(e) {
          console.log(e, 'dragging.......marker......')
          //const {  lat, lng  } = e.lnglat
          this.setPosition(e.lnglat)
        },
        dragend(e) {
          console.log(e, 'dragging.......marker......end')
          //const {  lat, lng  } = e.lnglat
          this.setPosition(e.lnglat)
        }
      },

      districtSearch: null,
      polygons: [],

      province: [],
      city: [],
      district: [],
      selectProvice: '420000',
      selectCity: null,
      selectDistrict: null,
      selectType: "gd",
      types: [{ label: "广告牌", value: "gd" }],
      gdData: [
          {
            params: [
              { label: "名称", value: '广告1', type: 'text', field: 'name' },
              { label: "位置", value: [114.139535, 30.537062] , type: 'label', field: 'position' },
            ]
          },
          {
            params: [
              { label: "名称", value: '广告2', type: 'text', field: 'name' },
              { label: "位置", value: [114.053018, 30.476128] , type: 'label', field: 'position' },
            ]
          },
          {
            params: [
              { label: "名称", value: '广告3', type: 'text', field: 'name' },
              { label: "位置", value: [114.053704, 30.581408] , type: 'label', field: 'position' },
            ]
          },
          {
            params: [
              { label: "名称", value: '广告4', type: 'text', field: 'name' },
              { label: "位置", value: [114.156014, 30.447718] , type: 'label', field: 'position' },
            ]
          }
      ],
      mouseTool: null,
      overlays: [],
      showimg: false,
      srcimg: demoImage
    };
  },

  methods: {
    saveData() {
      this.$message({
        type: 'success',
        message: '保存成功'
      })
      console.log(this.gdData, this.selectProvice, this.selectCity, this.selectDistrict)
    },

    searchArea() {
      const vm = this;
      const district = new window.AMap.DistrictSearch({
        subdistrict: 1, //返回下一级行政区
        showbiz: false //最后一级返回街道信息
      });
      district.search("中国", function(status, result) {
        if (status == "complete") {
          vm.getData(result.districtList[0]);
        }
      });
      this.districtSearch = district;
    },
    getData(data, level) {
      var bounds = data.boundaries;
      if (bounds) {
        for (let i = 0, l = bounds.length; i < l; i++) {
          var polygon = new window.AMap.Polygon({
            map: amapManager._map,
            strokeWeight: 1,
            strokeColor: "#0091ea",
            fillColor: "#80d8ff",
            fillOpacity: 0.2,
            path: bounds[i],
            bubble: true,
          });
          this.polygons.push(polygon);
        }
        amapManager._map.setFitView(); //地图自适应
      }

      //清空下一级别的下拉列表
      if (level === "province") {
        this.city = [];
        this.district = [];
        this.selectCity = null;
        this.selectDistrict = null;
      } else if (level === "city") {
        this.district = [];
        this.selectDistrict = null;
      }

      var subList = data.districtList;
      console.log(subList);
      if (subList) {
        var curlevel = subList[0].level;

        const curList = [];

        for (let i = 0, l = subList.length; i < l; i++) {
          let { name, level, center, adcode } = subList[i];

          let sub = {
            label: name,
            level,
            center,
            value: adcode
          };
          curList.push(sub);
        }
        this[curlevel] = curList;
      }
    },
    search(adcode, level) {
      return new Promise((resolve, reject)=>{
        //清除地图上所有覆盖物
        for (var i = 0, l = this.polygons.length; i < l; i++) {
          this.polygons[i].setMap(null);
        }

        this.districtSearch.setLevel(level); //行政区级别
        this.districtSearch.setExtensions("all");
        //行政区查询
        //按照adcode进行查询可以保证数据返回的唯一性
        const vm = this;
        this.districtSearch.search(adcode, function(status, result) {
          if (status === "complete") {
            vm.getData(result.districtList[0], level);
            resolve()
          }else{
            reject()
          }
        });
      })

    },
    setCenter(adcode) {
      let option;
      for (let item of this.district) {
        if (item.value == adcode) {
          option = item;
        }
      }
      if (!option) return;
      amapManager._map.setCenter(option.center);
    },
    addData(marker) {
          console.log(marker.getPosition(), 'data position')
          const {  lat, lng  } = marker.getPosition()
          const markerData = {
            params: [
              { label: "名称", value: '广告', type: 'text', field: 'name' },
              { label: "位置", value: [lng, lat] , type: 'label', field: 'position' },
              // { label: "显示图片", value: "" , type: 'text', field: 'img' }
            ]
          }
          this.gdData.push(markerData)
    },
    getGdName(marker) {
      const index = this.overlays.indexOf(marker)
      const data = this.gdData[index]
      console.log(data, 'getGdName......')
      return data.params[0].value
    },
    addOverlay() {
      if (!this.mouseTool) return
      var options = {
          // offset: new AMap.Pixel(-15, -30),
          draggable: true,
          clickable: true,
          content: ''
        }
      this.mouseTool['marker'](options)
    },
    addMarkers(){
        var options = {
          // offset: new AMap.Pixel(-15, -30),
          draggable: true,
          clickable: true,
          content: ''
        }
        this.gdData.forEach((item)=>{
            const position = item.params[1].value
            const marker = new AMap.Marker({...options, position: position})
            marker.setMap(amapManager._map);
            this.overlays.push(marker)
            this.setLabel(marker)
            this.addMarkerEvents(marker)
        })
    },
    disableMouse() {
      if (!this.mouseTool) return
      this.mouseTool.close()
    },
    enableMouse() {
      this.addOverlay()
    },
    setMarkerLabel(index) {
      const marker = this.overlays[index]
      this.setLabel(marker)
    },
    setLabel(marker) {
      if(!marker) return
      const gdName = this.getGdName(marker)
      marker.setLabel({
        content: `${gdName}`,
        offset: new AMap.Pixel(0, -30),
        direction: 'center'
      })
    },
    addMarkerEvents(marker) {
      
      const vm = this

      marker.on('click', function(e) {
        console.log(e, 'mark click....pipe')
        vm.showimg = true
        vm.disableMouse()
      })

      marker.on('dragging', function(e) {
        console.log(e, 'dragging.......pipe......')
       // let { lat, lng } = e.lnglat
        this.setPosition(e.lnglat)
      })

      marker.on('dragend', function(e) {
        console.log(e, 'dragging.......pipe......end')
        const idx = vm.overlays.indexOf(this)
        const currentData = vm.gdData[idx]
        let { lat, lng } = e.lnglat
        for(let item of currentData.params) {
          if(item.field=='position') {
            item.value=[lng, lat]
          }
        }
        vm.gdData.splice(idx, 1, currentData)
        this.setPosition(e.lnglat)
      })
    },
    loadMouseTools() {
      const vm = this

        console.log(22222)
        const mouseTool = new AMap.MouseTool(amapManager._map)

        mouseTool.on('draw', function(e) {
          console.log(e, 'draw begin....')
          vm.overlays.push(e.obj)
          vm.addData(e.obj)
          vm.setLabel(e.obj)
          vm.addMarkerEvents(e.obj)
        })
        vm.mouseTool = mouseTool
        vm.enableMouse()

    },
    removeAll() {
      this.gdData = []
       amapManager._map.remove(this.overlays)
       this.overlays = []
    },
    removeMarker(index) {
      this.gdData.splice(index, 1)
      const marker = this.overlays[index]
      amapManager._map.remove(marker)
      this.overlays.splice(index, 1)

    },
    remove(index, item) {
      console.log(index, item)
      this.removeMarker(index)
    },
    location(index, item) {
      console.log(index, item)
      let lanlnt
      for(let cur of item) {
        if(cur.field=='position') {
          lanlnt = cur.value
          break;
        }
      }
      if(!lanlnt) return
      amapManager._map.setCenter(lanlnt)
    }
  },
  mounted() {
    lazyAMapApiLoaderInstance.load().then(() => {
      this.searchArea();
      this.loadMouseTools()
      this.search(this.selectProvice, 'province').then(()=>{
        this.selectCity = '420100'
        this.search(this.selectCity, 'city').then(()=>{
          this.addMarkers()
        })
      })

    });
  }
};
</script>
<style lang="scss">
.home {
  height: 100vh;
  width: 100%;
  .row-container {
    height: 100%;
    width: 100%;
  }
  .left {
    //flex:1;
    .filter-params {
      padding: 20px;
    }
  }
  .right {
    height: 100%;
    //width: 80%;
    position: relative;
  }

  .search-area .el-select {
    width: 100%;
  }
  .el-dialog__body {
    height: calc(100% - 60px);
    padding: 0;
  }
}
</style>>
